﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RH.Common.Extensions;
using RH.Domain;
using RH.Web.ViewModels;
using RH.Web.Utility;
using AutoMapper;
using System.Data;
using RH.Web.ViewModels.UtilityModels;

namespace RH.Web.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class ContentController : BaseController
    {
		private AppEntities _Context = new AppEntities();
        
		#region Constructors
		public ContentController()
		{
		}

		public ContentController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods
        public ActionResult Index()
        {
            return View();
        }
		/// <summary>
        /// Gets a Content from Database to edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public ActionResult Edit(int id = 0)
        {
            Content entity = id == 0 ? new Content() : _Context.Contents.FirstOrDefault(P => P.ID == id);            
            ContentViewModel viewModel = Mapper.Map<Content, ContentViewModel>(entity);             
            return View(viewModel);
        }

        public ActionResult List()
        {
            UtilityDAO dao = new UtilityDAO();
            RH.Domain.DbParameter[] parameters = new[]{
                new RH.Domain.DbParameter("@ContentID", 0)
            };
            DataSet ds = dao.GetDataSet(DbObject.SP.GET_CONTENT, parameters, true);
            //DataTable dt = BuildDataTable();
            //DateTime start = DateTime.Now;
            ListConfig config = RH.Web.ViewModels.UtilityModels.ListConfigBuilder.Build(
                @"Info{ ID | Title | Created | Modified | Modified By | Url }, 
                Details{Summery | Description}",
                ds.Tables[0], "/Admin/Content/Edit/{0}");

            //Picture{Image:<img src='/ProductImages/{0}' alt='{1}' title='{2}' />(ThumbImage ~ ID ~ Name)},
            //Description{Description}

            //ViewBag.ListConfig = config;
            ViewData[AppConstants.ViewDataKeys.LIST_CONFIG] = config;
            return View();
        }

		/// <summary>
        /// Saves Content Information into the Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
		[HttpPost]
		public ActionResult Edit(ContentViewModel viewModel)
        {
			if (!ModelState.IsValid)
                return View(viewModel);
            if (_Context.IsDuplicateContent(viewModel.Title.ToSeoUrl(), viewModel.ID))
            {
                ModelState.AddModelError("Title", "Sorry! this title already exists. Choose another.");
                return View(viewModel);
            }

			Content entity = null;
            if (viewModel.ID == 0)
            {
                entity = new Content();
                _Context.AddToContents(entity);

            }
            else
            {
                entity = _Context.Contents.FirstOrDefault(P => P.ID == viewModel.ID);
                //viewModel.Created = entity.Created.ToString();
            }
            entity = Mapper.Map<ContentViewModel, Content>(viewModel, entity);

            entity.ModifiedBy = SessionCache.CurrentUser.ID;
            if (viewModel.ID == 0)
            {
                entity.Created = DateTime.Now;
            }           
            entity.Modified = DateTime.Now;
            entity.Url = viewModel.Title.ToSeoUrl();

            _Context.SaveChanges();
            
            ///Rebuild the Content and Company Route Cache, and re-map them in the global routing cache            
            MvcApplication.RefreshRoutes(true);

            return RedirectToAction("List");        
        }


        public ActionResult ViewContent(string ContentTitle = "" )
        {
            UtilityDAO dao = new UtilityDAO();
            RH.Domain.DbParameter[] parameters = new[]{
                new RH.Domain.DbParameter("@ContentID", (ContentTitle=="AboutUs")? ConfigReader.AboutUs:
                                                            (ContentTitle=="OurServices")? ConfigReader.OurServices:
                                                            (ContentTitle=="FAQ")? ConfigReader.FAQ:
                                                            (ContentTitle=="ContactUs")? ConfigReader.ContactUs:0
                                            )
            };
            DataSet ds = dao.GetDataSet(DbObject.SP.GET_CONTENT, parameters, true);

            if (ds.Tables[0].Rows.Count != 0)
            {
                ViewBag.ContentTitle = ds.Tables[0].Rows[0]["Title"].ToString();
                ViewBag.Summery = ds.Tables[0].Rows[0]["Summery"].ToString();
                ViewBag.Description = ds.Tables[0].Rows[0]["Description"].ToString();
            }

            return View();
        }

		#endregion Action Methods
		
		#region Helper Methods

        #endregion			
    }
}
